import requests
from bs4 import BeautifulSoup

# 设置请求头，模拟浏览器访问，避免被反爬
HEADERS = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
    'Referer': ''
}


def fetch_page(url, headers=None):
    """获取网页内容"""
    if headers is None:
        headers = HEADERS
    response = requests.get(url, headers=headers)
    response.encoding = 'utf-8'
    return response


def info_details(to_url):
    """获取并解析电影详情页信息"""
    response = fetch_page(to_url)

    # 检查请求是否成功
    if response.status_code == 200:
        html_content = response.text
        soup = BeautifulSoup(html_content, 'html.parser')

        try:
            content_info = soup.find("div", {"id": "wrapper"}).find("div", {"id": "content"})

            title_movie = content_info.find("h1").find("span").text.strip()
            print("电影名称：", title_movie)

            details_all = content_info.find("div", {"class": "article"}).find("div", {"class": "subjectwrap clearfix"})
            left_details_main = details_all.find("div", {"class": "subject clearfix"})
            right_details_main = details_all.find("div", {"id": "interest_sectl"})

            details_main = left_details_main.find("div", {"id": "info"}).text.strip()
            print(details_main)

            score_movie = right_details_main.find("div", {"class": "rating_self clearfix"}).find("strong").text.strip()
            score_movie_count = right_details_main.find("div", {"class": "rating_self clearfix"}).find("a", {
                "class": "rating_people"}).text.strip()
            print("豆瓣评分:", score_movie, score_movie_count)

            review_short = content_info.find("div", {"id": "comments-section"})
            review_short_title = review_short.find("h2").get_text(strip=True)
            print(review_short_title)

            hot_review_short_list = review_short.find_all("div", {"class": "comment-item"})

            print("前几条内容如下：")
            i = 1
            for line in hot_review_short_list:
                try:
                    people_review = line.find("span", {"class": "comment-info"}).find("a").get_text(strip=True)
                    review_detail = line.find("p", {"class": "comment-content"}).get_text(strip=True)
                    print(i, people_review, ":", review_detail)
                    i += 1
                except AttributeError:
                    # print(f"第{i}条评论解析失败")
                    # i += 1
                    continue

            print("*" * 40)

        except AttributeError as e:
            print(f"页面结构解析失败: {e}")
    else:
        print(f"请求失败，状态码: {response.status_code}")


# 主程序入口
def main():
    url = 'https://movie.douban.com/chart'
    response = fetch_page(url)

    # 检查请求是否成功
    if response.status_code == 200:
        html_content = response.text
        soup = BeautifulSoup(html_content, 'html.parser')
        content_info = soup.find("div", {"id": "wrapper"}).find("div", {"id": "content"})

        title_main = content_info.find("h1").text
        print(title_main, end=" ")
        title_second = content_info.find("div", {"class": "article"}).find("h2").get_text(strip=True)
        print(title_second)

        details_lists = content_info.find("div", {"class": "article"}).find_all("div", {"class": "pl2"})
        print("*" * 40)
        for single_details in details_lists:
            new_url = single_details.find("a").get("href")
            info_details(new_url)
    else:
        print(f"请求失败，状态码: {response.status_code}")


if __name__ == "__main__":
    main()
